package samples;

import java.util.concurrent.atomic.AtomicInteger;

public class S02_PrintLess200Via2Threads_synchronized {
    private static final AtomicInteger counter = new AtomicInteger(0);
    private static final Object lock = new Object();
    private static final int MaxCount = 10;

    public static void test() {
        Thread thread01 = new Thread(S02_PrintLess200Via2Threads_synchronized::threadBody);
        Thread thread02 = new Thread(S02_PrintLess200Via2Threads_synchronized::threadBody);

        thread01.start();
        thread02.start();

        System.out.println(Thread.currentThread() + " exist successfully ");
    }

    private static void threadBody() {
        while (counter.get() < MaxCount) {
            synchronized (lock) {
                lock.notifyAll();
                System.out.println(Thread.currentThread() + ": " + counter.getAndIncrement());
                try {
                    if (counter.get() < MaxCount) {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println(Thread.currentThread() + " exist successfully ");
    }
}
